# 使用蓝图
import os

from flask import Blueprint, request, render_template, redirect, jsonify
from sqlalchemy.sql.functions import user
from unicodedata import category
from ..models.models_admin import *
from ..models.models import *
import time
from pathlib import Path

admin = Blueprint('admin',__name__)

# 装饰器:登陆验证
from functools import wraps
def login_required(fn):
    @wraps(fn)
    def inner(*args, **kwargs):
        user_id = request.cookies.get('user_id', None)
        if user_id:
            # 登陆过，进入后台管理页面
            user = AdminUserModel.query.get(int(user_id))
            request.user = user
            return fn(*args, **kwargs)
        else:
            return redirect('admin/login/')
    return inner


# 后台管理-首页
@admin.route('/admin/')
@admin.route('/admin/index/')
@login_required
def index():
    # 获取cookie，得到登录用户
    # user_id = request.cookies.get('user_id', None)
    # if user_id:
    #     # 登陆过，进入后台管理页面
    #     user = AdminUserModel.query.get(int(user_id))
        # categorys = CategoryModel.query.filter()
        # articles = ArticleModel.query.filter()
        # photos = PhotoModel.query.filter()
        user = request.user
        categorys = CategoryModel.query
        articles = ArticleModel.query
        photos = PhotoModel.query
        return render_template('admin/index.html',
                               username = user.name,
                               categorys = categorys,
                               articles = articles,
                               photos = photos)
    # else:
    #     # 如果没有登陆就踢回登录页面
    #     return render_template('/admin/login.html/')


# 后台管理-登录
@admin.route('/admin/login/',methods=['GET','POST'])
def admin_login():
    if request.method == 'GET':
       return render_template('admin/login.html')
    elif request.method == 'POST':
        # 用户名
        username = request.form.get('username')
        # 密码
        userpwd = request.form.get('userpwd')
        user = AdminUserModel.query.filter_by(name = username, passwd = userpwd).first()

        if user:
            # 登录成功后设置cookie
            response = redirect('/admin/index/')
            response.set_cookie('user_id', str(user.id), max_age=3600*24*7)
            return response
        else:
            return '登录失败'

# 后台管理-退出登录
@admin.route('/admin/logout/')
def admin_logout():
    response = redirect('/admin/login/')
    response.delete_cookie('user_id')
    return response

# 后台管理-分类管理
@admin.route('/admin/category/')
@login_required
def admin_category():
    user = request.user
    categorys = CategoryModel.query.all()
    return render_template('admin/category.html',
                           username = user.name,
                           categorys = categorys)

# 后台管理-添加分类
@admin.route('/admin/addcategory/', methods=['GET','POST'])
@login_required
def admin_addcategory():
    if request.method == 'POST':
        name = request.form.get('name')
        describe = request.form.get('describe')

        # 添加分类
        category = CategoryModel()
        category.name = name
        category.describe = describe

        try:
            db.session.add(category)
            db.session.commit()
        except Exception as e:
            print('e' ,e)
            db.session.rollback()
        return redirect('/admin/category/')
    else:
        return '添加失败'

# 后台管理-删除分类
@admin.route('/admin/delcategory/', methods=['GET','POST'])
@login_required
def admin_delcategory():
    if request.method == 'POST':
        id = request.form.get('id')
        category = CategoryModel.query.get(int(id))

        # 删除分类
        try:
            db.session.delete(category)
            db.session.commit()
        except Exception as e:
            print('e' ,e)
        return jsonify({'code':200, 'msg':'删除成功！！！'})
    else:
        return jsonify({'code': 400, 'msg': '删除失败！！！'})


# 后台管理-修改分类
@admin.route('/admin/updatecategory/<id>/', methods=['GET','POST'])
@login_required
def admin_updatecategory(id):
    if request.method == 'GET':
       category = CategoryModel.query.get(int(id))
       return render_template('admin/category_update.html', 
                              category = category,
                              username = request.user.name)
    elif request.method == 'POST':
        name = request.form.get('name')
        describe = request.form.get('describe')
        # 修改
        category = CategoryModel.query.get(int(id))
        category.name = name
        category.describe = describe
        try:
            db.session.add(category)
            db.session.commit()
        except Exception as e:
            print('e' ,e)
        return redirect('/admin/category/')
    else:
        return '修改失败！！！'

# 文章管理
@admin.route('/admin/article/')
@login_required
def admin_article():
    articles = ArticleModel.query.all()
    return render_template('admin/article.html',
                           username = request.user.name,
                          articles = articles)

# 文章管理-添加文章
@admin.route('/admin/addarticle/', methods=['GET','POST'])
@login_required
def admin_add_article():
    if request.method == 'GET':
        categorys = CategoryModel.query.all()
        return render_template('admin/article_add.html',
                               username = request.user.name,
                               categorys = categorys)
    elif request.method == 'POST':
        name = request.form.get('name')
        keywords = request.form.get('keywords')
        content = request.form.get('content')
        category = request.form.get('category')
        img = request.files.get('img')
        print('img:',img)
        print('img.filename:',img.filename)

        # 图片存储路径
        img_name = f'{time.time()}-{img.filename}'
        img_url = f'/static/home/uploads/{img_name}'
        print(img_url)
        try:
            # 添加文章
            article = ArticleModel()
            article.name = name
            article.keyword = keywords
            article.content = content
            article.category_id = category
            article.img = img_url

            db.session.add(article)
            db.session.commit()

        except Exception as e:
            db.session.rollback()
            db.session.flush()
            print('e' ,e)
            print()
        else:
            img_data = img.read()
            # 获取当前文件的Path对象
            current_file = Path(__file__)
            # 获取当前文件的目录路径
            base_dir = current_file.parent.parent
            base_dir_str = str(base_dir)
            img_url_str = str(img_url)
            print(base_dir_str + img_url_str)
            with open(base_dir_str + img_url_str, 'wb') as fp:
                fp.write(img_data)
                fp.flush()
        return redirect('/admin/article/')


# 文章管理-修改文章
@admin.route('/admin/updatearticle/<id>/', methods=['GET','POST'])
@login_required
def admin_update_article(id):
    categorys = CategoryModel.query.all()
    article = ArticleModel.query.get(int(id))
    if request.method == 'GET':
        return render_template('admin/article_update.html',
                               username = request.user.name,
                               categorys = categorys,
                               article = article)
    elif request.method == 'POST':
        name = request.form.get('name')
        keywords = request.form.get('keywords')
        content = request.form.get('content')
        category = request.form.get('category')
        img = request.files.get('img')
        print('img:', img)
        print('img.filename:', img.filename)

        # 图片存储路径
        img_name = f'{time.time()}-{img.filename}'
        img_url = f'/static/home/uploads/{img_name}'

        try:
            # 修改文章
            article.name = name
            article.keyword = keywords
            article.content = content
            article.category_id = category
            article.img = img_url

            db.session.commit()
        except Exception as e:
            db.session.rollback()
            db.session.flush()
            print('e', e)
            print()
        else:
            img_data = img.read()
            # 获取当前文件的Path对象
            current_file = Path(__file__)
            # 获取当前文件的目录路径
            base_dir = current_file.parent.parent
            base_dir_str = str(base_dir)
            img_url_str = str(img_url)
            print(base_dir_str + img_url_str)
            with open(base_dir_str + img_url_str, 'wb') as fp:
                fp.write(img_data)
                fp.flush()
        return redirect('/admin/article/')

# 文章管理-删除文章
@admin.route('/admin/delarticle/', methods=['GET','POST'])
@login_required
def admin_del_article():
    if request.method == 'POST':
        id = request.form.get('id')
        article = ArticleModel.query.get(int(id))
        try:
            db.session.delete(article)
            db.session.commit()
        except Exception as e:
            print('e' ,e)
            return jsonify({'code': 500, 'msg': '删除失败！！！'})
        return jsonify({'code':200,'msg':'删除成功！！！'})
    else:
        return jsonify({'code':400, 'msg':'请求失败'})